'''
Author: thinktanker thinktanker@163.com
Date: 2024-03-08 19:53:14
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2024-03-09 08:59:19
FilePath: \biliweb\main.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import asyncio
import subprocess
import re

command = ['python', 'test.py']


async def follow_output(process):
    """异步跟随输出并打印"""
    while True:
        # 使用 StreamReader 的 readlines() 方法异步读取一行
        line = await process.stdout.readline()
        if not line:
            break  # 没有更多输出了，退出循环
        decoded_line = line.decode().rstrip()
        print("O(∩_∩)O ", decoded_line)
        if re.findall(
                r"still waiting for uiautomation ready|Cannot find any visible node",
                decoded_line):
            process.terminate()
            await process.wait()
            # 创建异步子进程
            process = await asyncio.create_subprocess_exec(
                *command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


async def launchpy():
    # 创建异步子进程
    process = await asyncio.create_subprocess_exec(*command,
                                                   stdout=subprocess.PIPE,
                                                   stderr=subprocess.STDOUT)

    # 异步跟随输出
    await follow_output(process)

    # 等待子进程结束
    await process.wait()

    return process.returncode


def main():
    asyncio.run(launchpy())


# 运行主函数
if __name__ == "__main__":
    main()
